package model;

import java.util.*;

public class ModelUtil {

	public static <T extends IModel> void removeFromList(List<T> list, T item) {
		if (list != null && item != null) {
			T dataInCache = null;
			for (T t : list) {
				if (t.getId() == item.getId()) {
					dataInCache = t;
				}
			}
			if (dataInCache != null) {
				list.remove(dataInCache);
			}
		}
	}

	public static <T extends IModel> void updateList(List<T> list, T item) {
		ModelUtil.<T> removeFromList(list, item);
		list.add(item);
	}

	public static <T extends IModel> void updateList(List<T> list, List<T> items) {
		for (T item : items) {
			ModelUtil.<T> removeFromList(list, item);
		}
		for (T item : items) {
			list.add(item);
		}
	}

	public static <T extends IModel> T getFromList(List<T> list, int id) {
		T obj = null;
		for (T t : list) {
			if (t.getId() == id) {
				obj = t;
			}
		}
		return obj;
	}

	public static <T extends IModel> Date getLastUpdated(List<T> list) {
		Date updated = null;
		for (T t : list) {
			if (updated == null) {
				updated = t.getUpdated();
			} else {
				if (t.getUpdated().after(updated)) {
					updated = t.getUpdated();
				}
			}
		}

		return updated;
	}
	//Dat add getLastId method
	public static <T extends IModel> int getLastId(List<T> list) {
		int lastId = 0;
		for (T t : list) {
			if (t.getId() > lastId) {
				lastId = t.getId();
			} 
		}

		return lastId;
	}
	//
	

	public static <T extends IModel> void addToList(List<T> list, T item) {
		if (list == null) {
			list = new ArrayList<T>();
		}
		if (item != null) {
			list.add(item);
		}
	}

	public static List<ChecklistItemModel> findChecklistItemByPhase(List<ChecklistItemModel> items, int idPhase) {
		List<ChecklistItemModel> res = new ArrayList<ChecklistItemModel>();

		for (ChecklistItemModel item : items) {
			if (item.getIdPhase() == idPhase) {
				res.add(item);
			}
		}

		return res;
	}

}
